<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
    <head>
        <meta charset="UTF-8">
        <title>聊天主界面</title>
        {load href="__COMMON__/js/jquery.min.js,__COMMON__/js/bootstrap.min.js,__COMMON__/css/bootstrap.min.css,__STATIC__/index/css/style.css,__COMMON__/js/jquery.qqFace.js"/}
    </head>
    <body>
        <div class="container-fluid">
            <div class="box">
                <div id="top_box">
                    <div id="search_box">
                        <span class="glyphicon glyphicon-search"></span>
                    </div>
                    <div id="name_box">
                        <span class="nick">游客</span><span class="status online">(在线)</span>
                    </div>
                </div>
                <div id="left_box">
                    <ul class="list-group">
                       <?php foreach ($users as $key => $value):?>
                            <li class="list-group-item userList" toid="<?=$value['id']?>">
                                <div class="head_box">
                                    <img class="img-circle head_img" src="__IMAGE__/head_img/<?=$value['head_img']?>">
                                </div>
                                <div class="name_msg">
                                    <p class="msg_p0"><span><?=$value['nick_name']?></span><span class="msg_time"><?=$value['time']?></span></p>
                                    <p class="msg_p"><span class="lastmsg"><?=$value['lastMsg']?></span><span class="badge bd"><?=$value['noRead']?></span></p>
                                </div>
                            </li>
                        <?php endforeach;?> 
                      </ul>
                </div>
                <div id="message_box">
                    <ul class="list-group" id="msg_ul">
                        
                      </ul>
                </div>
                <div id="tool_box">
                    <ul class="fl">
                        <li class="sendEmoj emotion"><img src="/images/tool_img/emoj.png"></li>
                        <li class="sendImg"><img src="/images/tool_img/photo.png"></li>
                    </ul>
                    <input type="file" name="file" id="file" style="display:none" accept="image/*"/>
                </div>
                <div id="right_box_down">
                     <div id="input_box" class="input-group">
                         <textarea id="inp" class="inp" placeholder="输入..."></textarea>
                         <span class="input-group-btn sp">
                             <button type="button" class="btn btn-primary enter">发送</button>
                         </span>
                    </div>
                </div>
            </div>
        </div>
        <audio src="__MUSIC__/care.wav" id="care">如果浏览器不支持，提示用户</audio>
    </body>
</html>
<script>
    $(function(){
        var apiUrl = "/index.php/api/Chat/";
        var fromid = {$fromid};
        var toid = {$toid};
        var fromHead = '';
        var fromNick = '';
        var toHead = '';
        var toNick = '';
        var sTop = 956;
        var curpage = 2;
        
        var ws = new WebSocket("ws://127.0.0.1:8282");
        ws.onopen = function(){
            console.info("连接成功");
        }

        ws.onmessage = function(e){
            console.info(e.data);
            var msg_obj = JSON.parse(e.data);
            switch(msg_obj.type){
                case 'bind':
                    getHead(fromid,toid);
                    getNick(toid);
                    msgLoad(fromid,toid);
                    var bind_data = '{"type":"bind","fromid":"'+fromid+'"}';
                    ws.send(bind_data);
                    var isOnline = '{"type":"isOnline","fromid":"'+fromid+'","toid":"'+toid+'"}';
                    ws.send(isOnline);
                    break;
                case 'isOnline':
                    var statusText = '';
                    if(msg_obj.status){
                        statusText = '(在线)';
                        $('.status').removeClass('offline').addClass('online');
                    }else{
                        statusText = '(离线)';
                        $('.status').removeClass('online').addClass('offline');
                    }
                    $('.status').text(statusText);
                    break;
                case 'say':
                    if(toid == msg_obj.fromid){
                        var msg = msg_obj.msg;
                        $("#msg_ul").append('<li class="list-group-item toLi text" style="background-image:url('+toHead+')">'+replace_em(msg)+'</li>');
                        $('#message_box').scrollTop(sTop+=150);
                        $('#care')[0].play();
                    }else{
                          userListReload(msg_obj);
                    }
                    break;
                case 'sayImg':
                    if(toid == msg_obj.fromid){
                        var img_url = msg_obj.imgUrl;
                        $("#msg_ul").append('<li class="list-group-item toLi" style="background-image:url('+toHead+')"><img class="img" src="__IMAGE__/msg_img/'+img_url+'"></li>');
                        $('#message_box').scrollTop(sTop+=250);
                        $('#care')[0].play();
                    }else{
                            userListReload(msg_obj);
                    }
                    break;
                case 'save':
                    saveMsg(e.data);
                    break;
                default:

            }
        }
        
        $('#message_box').scroll(function(){
            var scrTop = $(this).scrollTop()
            console.info(scrTop)
            if(scrTop == 0){
                $.getJSON(apiUrl+'oldMsg',{fromid:fromid,toid:toid,curpage:curpage},function(e){
                     curpage += 1;
                     if(e.status == 1){
                        var msgArys = e.msg;
                        var html = '';
                        $.each(msgArys,function(index,ary){ 
                           if(toid == ary.fromid){
                               if(ary.type == 0){
                                   html += '<li class="list-group-item toLi text" style="background-image:url('+toHead+')">'+replace_em(ary.content)+'</li>';       
                               }else{
                                   html +='<li class="list-group-item toLi" style="background-image:url('+toHead+')"><img class="img" src="__IMAGE__/msg_img/'+ary.imgPath+'"></li>';
                               }
                           }else{
                               if(ary.type == 0){
                                   html += '<li class="list-group-item frLi text" style="background-image:url('+fromHead+')">'+replace_em(ary.content)+'</li>';
                               }else{
                                   html +='<li class="list-group-item frLi" style="background-image:url('+fromHead+')"><img class="img" src="__IMAGE__/msg_img/'+ary.imgPath+'"></li>';
                               }
                           }
                       });
                       $('#msg_ul').prepend(html);
                       $('#message_box').scrollTop(scrTop+=250);
                    }else{
                        console.info(e.msg);
                    }
                });
            }
        })
        
        $('.userList').click(function(){
            $(this).each(function(){
                  curpage = 2;
                  var obj = $(this);
                  if(obj.hasClass('back')) return false;
                  toid = obj.attr('toid');
                  getHead(fromid,toid);
                  getNick(toid);
                  msgLoad(fromid,toid);
                  var isOnline = '{"type":"isOnline","fromid":"'+fromid+'","toid":"'+toid+'"}';
                  ws.send(isOnline);
                  obj.addClass('back').siblings().removeClass('back');  
                  
                  $.getJSON(apiUrl+'changeMsgSta',{fromid:fromid,toid:toid},function(e){
                       obj.children('.name_msg').children('.msg_p').children('.bd').text('');
                  });
            })
        })
        
        $('.sendImg').click(function(){
            $('#file').click();
        });
        
        $('#file').change(function(){
            oData = new FormData();
            oData.append('fromid',fromid);
            oData.append('toid',toid);
            oData.append('file',$(this)[0].files[0]);
            if($(this)[0].files[0].size > 204800){
                alert("图片限制200kb");
                return false;
            }
            
            var oReq = new XMLHttpRequest();
            oReq.open('post',apiUrl+'msgImg',true);
            oReq.onload = function(e){
                var response = JSON.parse(oReq.response);
                if(response.status == 1){
                     var img_data = '{"type":"sayImg","imgUrl":"'+response.imgUrl+'","fromid":"'+fromid+'","toid":"'+toid+'"}';
                     ws.send(img_data);
                     $("#msg_ul").append('<li class="list-group-item frLi" style="background-image:url('+fromHead+')"><img class="img" src="__IMAGE__/msg_img/'+response.imgUrl+'"></li>');
                      $('#message_box').scrollTop(sTop+=250);
                }else{
                    alert(response.msg)
                }
            }
            $(this).val('');            //清空input[type=file]的值,否则change事件只能触发一次
            oReq.send(oData);
        })
        
        $('.enter').click(function(){
            sendMsg();
        })
        
        $(document).keydown(function(event){
            var e = event ? event:window.event;
            if(e.keyCode == 13){
                sendMsg(); 
            }          
        })
        
          $('.emotion').qqFace({
		assign:'inp', 
		path:'__IMAGE__/arclist/'	//表情存放的路径

	});
        
        function saveMsg(msg){
            $.post(apiUrl+'saveMsg',{msg:msg},function(e){});
        }
        
        function sendMsg(){
            var inpContent = $.trim($('.inp').val());
            if(inpContent == ''){alert('不能发送空内容');return false};
            var data = '{"type":"say","msg":"'+inpContent+'","fromid":"'+fromid+'","toid":"'+toid+'"}';
            ws.send(data);
            $('.inp').val('');
            $("#msg_ul").append('<li class="list-group-item frLi text" style="background-image:url('+fromHead+')">'+replace_em(inpContent)+'</li>');
            $('#message_box').scrollTop(sTop+=150);
        }
        
        function getHead(fromid,toid){
            $.getJSON(apiUrl+'getHead',{fromid:fromid,toid:toid},function(e){
                fromHead = '__IMAGE__/head_img/'+e.fromHead;
                toHead = '__IMAGE__/head_img/'+e.toHead;
            })
        }
        
        function getNick(toid){
            $.getJSON(apiUrl+'getNickAjax',{toid:toid},function(e){
                $('.nick').text(e.nickName);
            })
        }
        
        function msgLoad(fromid,toid){
            $.getJSON(apiUrl+'msgLoad',{fromid:fromid,toid:toid},function(e){
                 $("#msg_ul").html('');
                var msgArys = e.msg;
                if(msgArys != ''){
                    $.each(msgArys,function(index,ary){
                        if(toid == ary.fromid){
                            if(ary.type == 0){
                              $("#msg_ul").append('<li class="list-group-item toLi text" style="background-image:url('+toHead+')">'+replace_em(ary.content)+'</li>');
                            }else{
                              $("#msg_ul").append('<li class="list-group-item toLi" style="background-image:url('+toHead+')"><img class="img" src="__IMAGE__/msg_img/'+ary.imgPath+'"></li>');
                            }
                        }else{
                            if(ary.type == 0){
                                $("#msg_ul").append('<li class="list-group-item frLi text" style="background-image:url('+fromHead+')">'+replace_em(ary.content)+'</li>');
                            }else{
                                $("#msg_ul").append('<li class="list-group-item frLi" style="background-image:url('+fromHead+')"><img class="img" src="__IMAGE__/msg_img/'+ary.imgPath+'"></li>');
                            }
                        }
                    });
                $('#message_box').scrollTop(sTop);
            }
            })
        }
        
        function userListReload(msg_obj){
                 var text_num = parseInt($('li[toid="'+msg_obj.fromid+'"]').children('.name_msg').children('.msg_p').children('.bd').text());
                 if(isNaN(text_num)){
                      $('li[toid="'+msg_obj.fromid+'"]').children('.name_msg').children('.msg_p').children('.bd').text(1);
                 }else{
                      $('li[toid="'+msg_obj.fromid+'"]').children('.name_msg').children('.msg_p').children('.bd').text(text_num+1);
                 }
                      $('li[toid="'+msg_obj.fromid+'"]').children('.name_msg').children('.msg_p0').children('.msg_time').text(timestampToTime(msg_obj.time));
                      $('li[toid="'+msg_obj.fromid+'"]').children('.name_msg').children('.msg_p').children('.lastmsg').html(replace_em(msg_obj.content));
        }
        
        function replace_em(str){

            str = str.replace(/\</g,'&lt;');

            str = str.replace(/\>/g,'&gt;');

            str = str.replace(/\n/g,'<br/>');

            str = str.replace(/\[em_([0-9]*)\]/g,'<img src="__IMAGE__/arclist/$1.gif" border="0" />');

            return str;

        }
        
        function timestampToTime(timestamp) {
            var date = new Date(timestamp * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
            Y = date.getFullYear() + '-';
            M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
            D = date.getDate() + ' ';
            h = date.getHours() + ':';
            m = date.getMinutes() + ':';
            s = date.getSeconds();
            return Y+M+D+h+m+s;
    }
    
     $('li[toid="'+toid+'"]').addClass('back');
    })
</script>
